<template>
  <el-dialog :visible="visible" title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)" @close="dialogClose" @open="fetchPermissionList">
    <!-- 权限点树形数据 -->
    <el-tree
      ref="treeRef"
      :data="treeList"
      show-checkbox
      node-key="id"
      default-expand-all
      :props="defaultProps"
      check-strictly
    />
    <!-- 按钮区域 -->
    <template #footer>
      <div style="text-align: right;">
        <el-button @click="$emit('dialog-close')">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissionList, checkPermission, getDetail } from '@/api'
import findSon from '@/utils/findSon'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      treeList: []
    }
  },
  methods: {
    // 弹窗关闭，执行的回调
    dialogClose() {
      this.$emit('dialog-close')
    },
    async fetchPermissionList() {
      // 发送请求, 获取所有权限点列表
      const res = await getPermissionList()
      this.treeList = findSon(res.data, '0')
      const { data: { permIds }} = await getDetail(this.roleId)
      this.$refs.treeRef.setCheckedKeys(permIds)
    },
    async submit() {
      await checkPermission({ id: this.roleId, permIds: this.$refs.treeRef.getCheckedKeys() })
      this.$message.success('分配角色成功')
      this.dialogClose()
    }
  }
}
</script>
